<template>
  <div>
    <el-tree
      :data="treeData"
      class="custom-tree"
      :default-expand-all="true"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.func_name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            v-if="data.func_key === ''"
            @click.native="beginAdd(data)"
          >
            <i class="el-icon-folder-add"> </i>
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="data.func_id !== 0"
            @click.native="beginEditor(data)"
          >
            <i class="el-icon-edit-outline"> </i>
          </el-button>
          <el-button type="text" size="mini" v-if="data.func_id !== 0">
            <i class="el-icon-delete" @click="remove(node, data)"> </i>
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="提示" :visible="edit.isEdit" width="50%">
      <el-form
        ref="ruleForm"
        label-width="100px"
        :model="edit.model"
        status-icon
        :rules="edit.rules"
      >
        <el-form-item label="功能类型">
          <el-radio-group
            v-model="edit.isLeaf"
            :disabled="!(edit.isMode && edit.model.func_fid === 0)"
          >
            <el-radio :label="false">非叶子节点</el-radio>
            <el-radio :label="true">叶子节点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级功能">
          <el-select
            v-model="edit.model.func_fid"
            :disabled="!(edit.isLeaf && !edit.isMode)"
          >
            <el-option :value="0" label="Root"> </el-option>
            <el-option
              v-for="item in list.filter((item) => item.func_key === '')"
              :key="item.func_id"
              :value="item.func_id"
              :label="item.func_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="功能名称" prop="func_name">
          <el-input v-model.trim="edit.model.func_name"></el-input>
        </el-form-item>
        <el-form-item label="功能对应组件" prop="func_key" v-if="edit.isLeaf">
          <el-select v-model="edit.model.func_key">
            <el-option
              v-for="(value, key) in Views"
              :key="key"
              :value="key"
              :label="value.name"
              :disabled="list.some((item) => item.func_key === key)"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="saveInfo">确 定</el-button>
        <el-button @click.native="edit.isEdit = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Views from "../index.js";
// 通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions } = createNamespacedHelpers("func");
export default {
  name: "Func",
  inject : ["reload"],
  data() {
    return {
      Views,
      edit: {
        isEdit: false,
        isMode: true,
        isLeaf: true,
        model: {
          func_id: 0,
          func_name: "",
          func_key: "",
          func_fid: -1,
        },
        rules: {
          func_name: [
            {
              validator: (rule, value, callback) => {
                let { func_id, func_fid } = this.edit.model;
                if (value === "") callback(new Error("*请输入功能名称"));
                else if (value.length < 2 || value.length > 10)
                  callback(new Error("*只能输入2-10位字符"));
                else if (
                  this.list.some(
                    (item) =>
                      item.func_id !== func_id &&
                      item.func_fid === func_fid &&
                      item.func_name === value
                  )
                )
                  callback(new Error("*功能名称重复"));
                else callback();
              },
              trigger: "blur",
            },
          ],
          func_key: [
            {
              validator: (rule, value, callback) => {
                if (this.edit.isLeaf && !value)
                  callback(new Error("*功能对应组件不能为空"));
                else callback();
              },
              trigger: "change",
            },
          ],
        },
      },
    };
  },
  methods: {
    // 直接取出来
    ...mapActions(["add","update"]),
    // 重命名
    ...mapActions({initFunc : "init",removeFunc : "remove"}),
    initForm() {
      if (this.$refs.ruleForm) this.$refs.ruleForm.resetFields();
    },
    saveInfo() {
      this.$refs.ruleForm
        .validate()
        .then(async (res) => {
          if (this.edit.isMode) {
            // 新增状态
            // this.edit.model.func_id =
            //   this.list[this.list.length - 1].func_id + 1;
            await this.add(JSON.parse(JSON.stringify(this.edit.model)));
          } else {
            //  编辑状态
           await this.update(JSON.parse(JSON.stringify(this.edit.model)));
          }
          this.edit.isEdit = false;
          this.reload();
        })
        .catch((err) => {
          console.log("校验失败");
        });
    },
    beginAdd(data) {
      this.initForm();

      this.edit.model.func_id = 0;
      this.edit.model.func_name = "";
      this.edit.model.func_key = "";
      this.edit.model.func_fid = data.func_id;

      this.edit.isLeaf = data.func_fid === 0;

      this.edit.isMode = true;
      this.edit.isEdit = true;
    },
    beginEditor(data) {
      this.initForm();
      this.edit.model.func_id = data.func_id;
      this.edit.model.func_name = data.func_name;
      this.edit.model.func_key = data.func_key;
      this.edit.model.func_fid = data.func_fid;

      this.edit.isLeaf = data.func_key !== "";
      this.edit.isMode = false;
      this.edit.isEdit = true;
    },
    remove(node, data) {
      this.$confirm(`此操作将永久删除${data.func_name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.removeFunc(data.func_id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.reload();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  computed: {
    ...mapState(["list"]),
    treeData() {
      let list = JSON.parse(JSON.stringify(this.list)),
        result = [
          {
            func_id: 0,
            func_name: "Root",
            func_key: "",
            func_fid: -1,
            children: [],
          },
        ];
      list
        .filter((item1) => item1.func_fid === 0)
        .forEach((item) => {
          if (!item.func_key) {
            let child = list.filter((func) => func.func_fid === item.func_id);
            if (child.length) {
              item.children = [];
              child.forEach((func_child) => item.children.push(func_child));
            }
          }
          result[0].children.push(item);
        });

      return result;
    },
  },
  async created() {
    this.initFunc();
  },
};
</script>

<style></style>
